package com.ruoyi.common.utils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.UUID;

import javax.annotation.Resource;
import javax.persistence.Id;

import com.ruoyi.common.dao.service.UidGenService;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.xfvape.uid.UidGenerator;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.UUIDGenerator;
import org.springframework.beans.factory.annotation.Autowired;

public class IDUtils extends UUIDGenerator {

	private UidGenService uidGenService;


	public UidGenService getUidGenService() {
		if(uidGenService == null){
			uidGenService = SpringUtils.getBean(UidGenService.class);
		}
		return uidGenService;
	}

	@Override
	public Serializable generate(SharedSessionContractImplementor session, Object object) {
		try {
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Id annotation = field.getAnnotation(Id.class);
				if (Objects.nonNull(annotation) && Objects.nonNull(field.get(object))) {
					return (Serializable) field.get(object);
				}
			}
		} catch (Exception e) {

		}

		return getUidGenService().getUid();

	}
}